package com.xz.xzutils.components.editor;

import com.intellij.lang.Language;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.testFramework.LightVirtualFile;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;
import java.util.UUID;

/**
 * @author DONG.WANG17@HAND-CHINA.COM
 * @since 2025/2/26-02-26 16:08
 */
public class MyEditorHelper {
    @NotNull
    public static Editor createEditor(@NotNull Project project, @NotNull String virtualFileName) {
        FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(virtualFileName);
        // 创建虚拟文件
        LightVirtualFile virtualFile = new LightVirtualFile(virtualFileName, fileType, "");
        // 创建 Document
        Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
        // 创建 Editor 实例
        EditorFactory editorFactory = EditorFactory.getInstance();
        return editorFactory.createEditor(Objects.requireNonNull(document), project);
    }

    public static Editor createEditor(@NotNull Project project, @NotNull FileTypeByExtension fileTypeEnum) {
        FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(fileTypeEnum.name());
        String virtualFileName = UUID.randomUUID().toString().replace("-", "") + "." + fileTypeEnum.name();
        LightVirtualFile virtualFile = new LightVirtualFile(virtualFileName, fileType, "");
        // 创建 Document
        Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
        // 创建 Editor 实例
        EditorFactory editorFactory = EditorFactory.getInstance();
        return editorFactory.createEditor(Objects.requireNonNull(document), project);
    }

    public static <T extends Language> Editor createEditor(@NotNull Project project, @NotNull String virtualFileName, @NotNull T lang) {
        LightVirtualFile virtualFile = new LightVirtualFile(virtualFileName, lang, "");
        // 创建 Document
        Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
        // 创建 Editor 实例
        EditorFactory editorFactory = EditorFactory.getInstance();

        return editorFactory.createEditor(Objects.requireNonNull(document), project);
    }
}
